package cn.edu.nju.sharing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import cn.edu.nju.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class ImageGetter {
	private Uri imageUri;
	private Activity context;
	private AlertDialog.Builder pictureUploadDialog;
	private final int FILE_PICTURE = 1;
	private final int CAMERA_PICTURE = 0;
	
	public ImageGetter(Activity activity){
		this.context = activity;
		pictureUploadDialog = new Builder(context);
		pictureUploadDialog.setTitle(R.string.upload_picture);
		pictureUploadDialog.setIcon(android.R.drawable.ic_dialog_info);
		String uploadFromFile = context.getString(R.string.upload_from_file);
		String uploadFromCamera = context.getString(R.string.upload_from_camera);
		String cancel = context.getString(R.string.cancel);
		pictureUploadDialog.setItems(new String[]{uploadFromCamera, uploadFromFile, cancel},
				new DialogInterface.OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						if(which == 0){
							Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
							File file = new File(Environment.getExternalStorageDirectory().getPath() + 
												File.separator + UUID.randomUUID().toString() + ".jpg");
							imageUri = Uri.fromFile(file);
							intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
							context.startActivityForResult(intent, CAMERA_PICTURE);
						}
						else if(which == 1){
							Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
							File file = new File(Environment.getExternalStorageDirectory().getPath() + 
									File.separator + UUID.randomUUID().toString() + ".jpg");
							imageUri = Uri.fromFile(file);
							intent.setType("image/*");
							String selectPictureSource = context.getString(R.string.select_picture_source);
							context.startActivityForResult(Intent.createChooser(intent, selectPictureSource), FILE_PICTURE);
						}
						else{
							dialog.dismiss();
						}
					}		
				});
	}
	
	public void startImageGetActivity(){		
		pictureUploadDialog.show();
	}
	
	public Uri handleActivityResult(int requestCode, int resultCode, Intent data){
		if(resultCode == context.RESULT_OK){
			if(requestCode == CAMERA_PICTURE){
				return imageUri;
			}
			else{
				if(data != null){
					// copy to temp file
					Uri selectedImageUri = data.getData();
					String filemanagerString = selectedImageUri.getPath();
					String selectedImagePath = getPath(selectedImageUri);
					
					File imageFile = null;
					if(selectedImagePath != null){
						imageFile = new File(selectedImagePath);
					}
					else if(filemanagerString != null){
						imageFile = new File(filemanagerString);
					}
					
					if(imageFile != null){
						try{
							File targetFile = new File(imageUri.getPath());
							if(!targetFile.exists()){
								targetFile.createNewFile();
							}
							InputStream in = null;
					        OutputStream out = null;
					        in = new FileInputStream(imageFile);
					        out = new FileOutputStream(targetFile);
					        
					        byte[] buffer = new byte[1024];
					        int read;
					        while((read = in.read(buffer)) != -1){
					        	out.write(buffer, 0, read);
					        }
					        
					        in.close();
					        in = null;
					        out.flush();
					        out.close();
					        out = null;
					        
					        return imageUri;
						} catch(Exception e){
							e.printStackTrace();
						}
					}
				}
			}
		}
		
		return null;
	}
	
	private String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.managedQuery(uri, projection, null, null, null);
        if(cursor!=null)
        {
            //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else return null;
    }
		
	public Bitmap decodeFile(File f, int imageSize){
		try{
			// decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
            
            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < imageSize || height_tmp / 2 < imageSize)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale++;
            }
            
            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		}
		catch (FileNotFoundException e) {
			
        }
        return null;
	}
}
